import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { getSearchResult, getSearchHotResult, getReset } from "../../redux/actions";
import { SearchBar, ListView, Toast, Icon } from "antd-mobile";
import "./index.scss";
import { KEYWORD } from '../../utils'

class Index extends Component {
  constructor(props) {
    super(props);
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2
    });
    this.state = {
      isHotShow: true,
      initData: [],
      dataSource: dataSource.cloneWithRows([]),
      offset: 0,
      pageTotal: 0,
      totalValue: 0,
      limit: 10,
      content: "",
      pageSize: 10,
      currentPage: 1,
      isLoading: true,
      height: (document.documentElement.clientHeight * 3) / 4
    };
  }

  componentDidMount() {
    this.props.getSearchHotResult();
    // console.log(this.state.initData);
    if (localStorage.getItem(KEYWORD)) {
      this.setState({
        initData: []
      });
    }
  }
  componentWillReceiveProps(nextProps) {
    const { temArr } = nextProps.searchResult;
    this.setState({
      initData: [...this.state.initData, ...temArr]
    }, () => {
      this.setState({
        dataSource: this.state.dataSource.cloneWithRows(this.state.initData)
      });
    });
  }
  componentWillUnmount() {
    this.props.getReset();
  }
  onEndReached = event => {
    if (this.state.isLoading && !this.state.hasMore) {
      return;
    }

    let currentPage = this.state.currentPage + 1;
    let limit = this.state.limit;
    let offset = (currentPage - 1) * limit;
    let content = this.state.content;
    let totalValue = this.props.searchResult["songCount"];
    console.log('totalValue', totalValue);
    let pageTotal =
      totalValue % limit == 0
        ? parseInt(totalValue / limit)
        : parseInt(totalValue / limit) + 1;
    this.setState(
      {
        isLoading: true,
        currentPage,
        offset,
        totalValue,
        pageTotal
      },
      () => { }
    );
    console.log(currentPage, pageTotal);
    if (currentPage < pageTotal) {
      this.props.getSearchResult(content, offset, limit);
    }

    this.setState({
      isLoading: false
    });
  };
  onCancel = () => {
    localStorage.removeItem(KEYWORD)
    this.setState({
      currentPage: 1,
      content: '',
      isHotShow: true,
      initData: [],
      dataSource: this.state.dataSource.cloneWithRows([])
    });
  };
  onFocus = () => {
    this.setState({
      isHotShow: false
    });
  };

  onSubmit = (hotkey) => {
    this.setState({
      isLoading: true,
      currentPage: 1
    });
    let { pageSize, content, currentPage } = this.state;
    let offset = (currentPage - 1) * pageSize;
    if (hotkey) {
      this.props.getSearchResult(hotkey, offset, pageSize);
      this.setState({
        isLoading: false,
        isHotShow: false,
        content: hotkey
      });
      localStorage.setItem(KEYWORD, hotkey)
    } else {
      if (content) {
        this.props.getSearchResult(content, offset, pageSize);
        this.setState({
          isLoading: false
        });
        localStorage.setItem(KEYWORD, hotkey)
      } else {
        Toast.fail("关键字不能为空");
      }
    }
  };
  render() {
    const separator = (sectionID, rowID) => (
      <div
        key={`${sectionID}-${rowID}`}
        style={{
          backgroundColor: "#F5F5F9",
          height: 8,
          borderTop: "1px solid #ECECED",
          borderBottom: "1px solid #ECECED"
        }}
      />
    );
    const row = (rowData, sectionID, rowID) => {
      return (
        <div key={rowData.id} className="m-search-list">
          <span className="iconfont m-search-list-l">&#xe9d5;</span>
          <span className="m-search-list-r">
            <span className="m-search-list-l-title-cls">{rowData.keyWord}</span>
            <span className="m-search-list-l-value-cls">
              {rowData.artistsName}-{rowData.albumName}
            </span>
          </span>
        </div>
      );
    };

    return (
      <div style={{ marginTop: 50, marginBottom: 50 }}>
        <SearchBar
          className="searchBar"
          onFocus={() => { this.onFocus() }}
          onCancel={() => this.onCancel()}
          onSubmit={value => this.onSubmit()}
          value={this.state.content}
          onChange={val => this.setState({ content: val })}
          placeholder="请输入关键字"
          ref={ref => (this.autoFocusInst = ref)}
        />
        {this.state.isHotShow ? (
          <div className="searchHot">
            <h3 className="result_tit">热门搜索</h3>
            {this.props.searchHotResult.map((item, index) => (
              <span key={index} onClick={() => {
                this.onSubmit(item.first)
              }}>{item.first}</span>
            ))}
          </div>
        ) : null}
        {this.state.initData && this.state.initData.length > 0 ? (
          <ListView
            style={{ marginTop: 100 }}
            ref={el => (this.lv = el)}
            dataSource={this.state.dataSource}
            renderFooter={() => (
              <div style={{ padding: 30, textAlign: "center" }}>
                {this.state.isLoading ? "loading..." : "Loaded"}
              </div>
            )}
            renderRow={row}
            renderSeparator={separator}
            pageSize={this.state.pageSize}
            useBodyScroll
            onScroll={() => {
              console.log("scroll");
            }}
            scrollRenderAheadDistance={500}
            onEndReached={this.onEndReached}
            onEndReachedThreshold={10}
          />
        ) : null}
      </div>
    );
  }
}
export default connect(
  state => ({
    searchResult: state.searchResult,
    searchHotResult: state.searchHotResult
  }),
  { getSearchResult, getSearchHotResult, getReset }
)(Index);
